package com.ruoyi.youtian.controller;

import com.ruoyi.common.constant.YouQiConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.YouTianThreadPool;
import com.ruoyi.common.utils.html.ScriptEngineUtil;
import com.ruoyi.gzmx_tag_history.service.IGzmx_tag_historyService;
import com.ruoyi.youtian.domain.vo.TEarlyWarningVo;
import com.ruoyi.youtian.domain.vo.TemplateSceneVO;
import com.ruoyi.youtian.service.*;
import com.ruoyi.youtian.threadConfig.AsyncAnalyseEarlyWarning;
import com.ruoyi.youtian.threadConfig.AsyncAnalyseFault;
import com.sun.jna.platform.win32.WinReg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/ScheduledTasks")
@Slf4j
public class YoutianController {



    @Autowired
    private ITemplateService templateService;

    @Autowired
    private IFaultRecordService faultRecordService;


    @Autowired
    private ITemplateDetailService templateDetailService;


    /**
     * 预警值进行比较
     */
    @Autowired
    private ITEarlyWarningService itEarlyWarningService;

    /**
     * 点位历史记录值
     */
    @Autowired
    private IGzmx_tag_historyService gzmx_tag_historyService;

    @Autowired
    private ITEarlyWarningRecordService itEarlyWarningRecordService;
    @Autowired
    private ITEarlyWarningRecordDetailService itEarlyWarningRecordDetailService;



    private static final ConcurrentHashMap<String, Boolean> myMap=new ConcurrentHashMap<>();

    private static final ConcurrentHashMap<String, Boolean> myMap2=new ConcurrentHashMap<>();
//    static
//    {
//        myMap = new ConcurrentHashMap<String, String>();
//        myMap.put("boolean", "flase");
//    }

    /**
     *  sys_job表中 job_id 为 7
     *  功能描述:
     *
     *  2.判断头节点 如果有超过上限, 或者低于下限, 触发异常分析
     *  3.异常分析逻辑:
     *
     *
     */
    @RequestMapping("/abnormal")
    public void monitorScenePoint() {

        try {
            if (myMap.containsKey("abnormal")&&myMap.get("abnormal")) {
                return;
            }
            myMap.put("abnormal",true);
            // 1.场景下 所有发布的模板, 找到模板下的头节点,(发布状态, 头节点, 未删除)
            TemplateSceneVO templateSceneVO = new TemplateSceneVO();
            templateSceneVO.setSourceTop(YouQiConstants.HEAD_NODE_TYPE);
            List<TemplateSceneVO> templateSceneVOList = templateService.selectSceneSourcePoint(templateSceneVO);
            log.info("templateSceneVOList: {}", LocalDateTime.now(), templateSceneVOList.size());
            //判断 异常头节点 , 大于上限 或者 小于下限 , 去重
            List<Long> templateIds = templateSceneVOList.stream()
                    .filter(vo -> vo.getPointValue() != null && vo.getUpperLimit() != null && vo.getLowerLimit() != null)
                    .filter(vo -> vo.getPointValue() > vo.getUpperLimit() || vo.getPointValue() < vo.getLowerLimit())
                    .filter(vo -> Objects.equals(1, vo.getStatus()))
                    //.filter(vo -> judgeOperation(vo))  // 根据自定义条件公式判断是否走这个模型进行分析
                    .map(TemplateSceneVO::getTemplateId)
                    .distinct()
                    .collect(Collectors.toList());
            log.info("{}_异常的场景templateId为: {}", LocalDateTime.now(), templateIds);

            // 2.多线程去执行每个流程
            templateIds.forEach(id -> {
                //启动异常分析流程
                YouTianThreadPool.getPatrolPool().
                        execute(new AsyncAnalyseFault("异常分析,templateId: " + id, templateService, faultRecordService, templateDetailService, id));

            });
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            myMap.put("abnormal",false);
        }
    }

    /**
     *
     * 判断自定义条件是否启用
     * 将目标点位的采集值和源点位的采集值带入公式计算
     * @param
     * @param vo 模板详情对象
     * @return
     */
    public boolean judgeOperation( TemplateSceneVO vo){
        String formulaTxt = vo.getFormulaText(); //formulaTxt 规则公式
        if (StringUtils.isNotEmpty(formulaTxt) && vo.getOperateRuleStatus() == 0 ){
            formulaTxt.replaceAll("\\{source_point_id}",vo.getPointValue()+"");
            formulaTxt.replaceAll("\\{target_point_id}",vo.getTargetValue().toString()+"");
        }
        return ScriptEngineUtil.eval(formulaTxt);
    }


    /**
     * 定时去监测
     */
    @RequestMapping("/earlywarning")
    public void monitorEarlyWaringPoint(){
        try {
            if (myMap2.containsKey("abnormal")&&myMap2.get("abnormal")) {
                return;
            }
            myMap2.put("abnormal",true);
        TEarlyWarningVo earlyWarningVo = new TEarlyWarningVo();
        earlyWarningVo.setStatus("0");
        List<TEarlyWarningVo> tEarlyWarningVoList = itEarlyWarningService.selectEarlyWarningVoList(earlyWarningVo);
        tEarlyWarningVoList.forEach(tEarlyWarning -> {
            // 预警监控
            YouTianThreadPool.getPatrolPool().
                    execute( new AsyncAnalyseEarlyWarning("预警监控"+ tEarlyWarning.getWarningCode(), itEarlyWarningService,  gzmx_tag_historyService,  itEarlyWarningRecordService,
                            itEarlyWarningRecordDetailService ,  faultRecordService, tEarlyWarning));

        });

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            myMap2.put("abnormal",false);
        }
    }
}
